package be.kul.osgi.ds.myagent;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.osgi.framework.Bundle;

import be.kul.osgi.ds.comminterface.MyEvent;
import be.kul.osgi.ds.comminterface.MyEventListener;
import be.kul.osgi.ds.irole.IRole;
import be.kul.osgi.ds.irole.ITask;
import be.kul.osgi.ds.messageservice.MessageObject;
import be.kul.osgi.ds.myagent.Role.RoleHandler;
import be.kul.osgi.ds.myagent.Role.TaskHandler;
import be.kul.osgi.ds.myagent.message.AskRole;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class AgentGui implements MyEventListener{

	private MyAgent a;
	private JFrame frmAgent;
	private JTextField text_portnumber;
	private JTextField text_multicastgroup;
	private JTextArea text_console;
	private JTextField text_message;
	private JTextField text_address;
	private JList list_tasks;
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					AgentGui window = new AgentGui();
					window.frmAgent.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public AgentGui(MyAgent agent) {
		this.a = agent;
		initialize();
		frmAgent.setVisible(true);
	}
	
	public AgentGui() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frmAgent = new JFrame();
		frmAgent.setTitle(this.a.name);
		frmAgent.setBounds(100, 100, 450, 300);
		frmAgent.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		//Tabbed panel
		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		frmAgent.getContentPane().add(tabbedPane, BorderLayout.CENTER);
		
		//main panel
		JPanel panel_main = new JPanel();
		tabbedPane.addTab("Main", null, panel_main, null);
		
		//Task panel
		JPanel panel_tasks = new JPanel();
		tabbedPane.addTab("Tasks", null, panel_tasks, null);
		panel_tasks.setLayout(new GridLayout(1, 3, 0, 0));
		
		list_tasks = new JList();
		
		list_tasks.setBorder(UIManager.getBorder("List.focusCellHighlightBorder"));
		panel_tasks.add(list_tasks);
		
		final JTextPane text_task_info = new JTextPane();
		panel_tasks.add(text_task_info);
		
		JPanel panel_task_buttons = new JPanel();
		panel_tasks.add(panel_task_buttons);
		panel_task_buttons.setLayout(new GridLayout(0, 1, 0, 0));
		
		JButton btn_ShareTask = new JButton("Share");
		panel_task_buttons.add(btn_ShareTask);
		
		JButton btnTaskRefresh = new JButton("Refresh");
		panel_task_buttons.add(btnTaskRefresh);
		
		
		
		//roles panel
		JPanel panel_roles = new JPanel();
		tabbedPane.addTab("Roles", null, panel_roles, null);
		panel_roles.setLayout(new GridLayout(1, 3, 0, 0));
		
		final JList list_roles = new JList(a.roles);
		
		list_roles.setBorder(UIManager.getBorder("List.focusCellHighlightBorder"));
		panel_roles.add(list_roles);
		
		final JTextPane text_role_info = new JTextPane();
		panel_roles.add(text_role_info);
		
		JPanel panel = new JPanel();
		panel_roles.add(panel);
		panel.setLayout(new GridLayout(0, 1, 0, 0));
		
		JButton btnExecute = new JButton("Execute");
		panel.add(btnExecute);
		
		JButton btnMakePackage = new JButton("Make Package");
		panel.add(btnMakePackage);
		
		JButton btnShare = new JButton("Share");
		panel.add(btnShare);
		
		JButton btnGetState = new JButton("Get State");
		panel.add(btnGetState);
		
		JButton btnSellRole = new JButton("Sell Role");
		panel.add(btnSellRole);
		
		JButton btnExportTasks = new JButton("Export Tasks");
		panel.add(btnExportTasks);
		
		JButton btnGetTask = new JButton("Get Task");
		panel.add(btnGetTask);
		
		
		//Communication Panel
		JPanel panel_communication = new JPanel();
		tabbedPane.addTab("Communication", null, panel_communication, null);
		panel_communication.setLayout(new GridLayout(2, 2, 0, 0));
		
		JPanel panel_1 = new JPanel();
		panel_communication.add(panel_1);
		panel_1.setLayout(new GridLayout(3, 2, 0, 0));
		
		JLabel lblPort = new JLabel("Port");
		panel_1.add(lblPort);
		
		text_portnumber = new JTextField();
		text_portnumber.setText("4567");
		panel_1.add(text_portnumber);
		text_portnumber.setColumns(10);
		
		JLabel multicastgroup = new JLabel("group Multicast");
		panel_1.add(multicastgroup);
		
		text_multicastgroup = new JTextField();
		text_multicastgroup.setText("224.0.0.123");
		panel_1.add(text_multicastgroup);
		text_multicastgroup.setColumns(10);
		
		JButton btnInitServer = new JButton("Init Server");
		panel_1.add(btnInitServer);
		JPanel panel_console = new JPanel();
		tabbedPane.addTab("Console", null, panel_console, null);
		panel_console.setLayout(null);
		
		JButton btnClearConsole = new JButton("clear console");
		
		text_console = new JTextArea();
		text_console.setText("console...");
		text_console.setBounds(0, 0, 405, 197);
		panel_console.add(text_console);
		btnClearConsole.setBounds(0, 208, 130, 23);
		panel_console.add(btnClearConsole);
		
		
		//Message Panel
		JPanel panel_message = new JPanel();
		tabbedPane.addTab("message", null, panel_message, null);
		panel_message.setLayout(null);
		
		JButton btnSendMessage = new JButton("Send Message");

		
		btnSendMessage.setBounds(10, 117, 189, 23);
		panel_message.add(btnSendMessage);
		
		text_message = new JTextField();
		text_message.setText("enter text...");
		text_message.setBounds(10, 38, 189, 68);
		panel_message.add(text_message);
		text_message.setColumns(10);
		
		JLabel label_message = new JLabel("Message");
		label_message.setBounds(27, 13, 46, 14);
		panel_message.add(label_message);
		
		text_address = new JTextField();
		text_address.setText("224.0.0.123");
		text_address.setBounds(242, 38, 159, 23);
		panel_message.add(text_address);
		text_address.setColumns(10);
		
		JLabel lblAddress = new JLabel("Address");
		lblAddress.setBounds(270, 13, 46, 14);
		panel_message.add(lblAddress);
		
		JButton btnTestMessageObject = new JButton("Test Stream");
		btnTestMessageObject.setBounds(12, 152, 187, 23);
		panel_message.add(btnTestMessageObject);
		
		JButton btnTestMessageId = new JButton("Test Message ID");
		
		btnTestMessageId.setBounds(10, 186, 189, 23);
		panel_message.add(btnTestMessageId);
		
		JButton btnTestAskmessage = new JButton("Test AskMessage");
		btnTestAskmessage.setBounds(241, 117, 159, 23);
		panel_message.add(btnTestAskmessage);
		
		
		//init the server
		btnInitServer.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				//Init serversocket
				String port = text_portnumber.getText();
				int portnumber = Integer.parseInt(port);
				String g = text_multicastgroup.getText();
				a.socket_init(portnumber, g);
			}
		});
		
		//clear the console
		btnClearConsole.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				text_console.setText("Console refreshed");
			}
		});
		
		//select a Role
		list_roles.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent arg0) {
				IRole r = (IRole)list_roles.getSelectedValue();
				try {
					text_role_info.setText((new RoleHandler(r,a)).getfeatures());
					text_role_info.setText((new RoleHandler(r,a)).SerializeFeatures());
					String g = (new RoleHandler(r,a)).SerializeFeatures();
					//Properties p = (new RoleHandler(r)).deSerializeFeatures(a.getXMLStreamService(), g);
					//text_role_info.setText(p.toString());
					} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (URISyntaxException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		
		//SendMessage
		btnSendMessage.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String s = text_message.getText();
				String l = text_address.getText();
				MessageObject o = new MessageObject(MessageObject.UNKNOWN);
				o.setContent(s);
				String xml = a.XMLStreamservice.toXML(o);
				a.getComm().sendmulticast(xml);
			}
		});
		
		
		//testMessageStream
		btnTestMessageObject.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String s = text_message.getText();
				IRole r = (IRole)list_roles.getSelectedValue();
				String g = new String();
				try {
					g = (new RoleHandler(r,a)).SerializeFeatures();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				MessageObject mo = new MessageObject(MessageObject.CFP);
				mo.setContent(g);
				mo.setOntology("ROLE-EXCHANGE");
				String mes = a.getMessageService().serialize(mo);
				String adr = text_address.getText();
				a.getComm().send(mes, adr);
			}
		});
		
		//Make package from selected Role
		btnMakePackage.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				IRole r = (IRole)list_roles.getSelectedValue();
				(new RoleHandler(r,a)).pack(a.bundledata);
			}
		});
		
		//execute role
		btnExecute.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				IRole r = (IRole)list_roles.getSelectedValue();
				//r.execution();
				(new RoleHandler(r,a)).exportState();
				(new RoleHandler(r,a)).importState();
				//r.exportState();
				//r.reInit();
			}
		});
		
		//get State
		btnGetState.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				IRole r = (IRole)list_roles.getSelectedValue();
				//(new RoleHandler(r,a)).getState();
				(new RoleHandler(r,a)).getDependencies();
			}
		});
		//sell role, sell Task
		btnSellRole.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
				IRole r = (IRole)list_roles.getSelectedValue();
				//(new RoleHandler(r,a)).sellRole(a.bundledata);
				(new RoleHandler(r,a)).SellTasks();
				//.sellRole("224.0.0.123");
				System.out.println("!!!action!!!");
			}
		});
		
		
		//export tasks
		btnExportTasks.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				IRole r = (IRole)list_roles.getSelectedValue();
				(new RoleHandler(r,a)).serializeTask();
			}
		});
		
		//Get Task
		btnGetTask.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				IRole r = (IRole)list_roles.getSelectedValue();
				URL url = null;
				try {
					url = new URL("http://localhost:" + a.getPort() + "/files/task.xml");
					//URL oracle = new URL("http://www.oracle.com/");
			        URLConnection yc;
					yc = url.openConnection();
			        BufferedReader in = new BufferedReader(new InputStreamReader(
			        yc.getInputStream()));
			        String inputLine;
			        StringBuilder x = new StringBuilder();
			        while ((inputLine = in.readLine()) != null) 
			        	 x.append(inputLine);
			        in.close();
			        String xml = x.toString();
			        System.out.println("XML inhoud : " + xml);
					IRole test = (new TaskHandler(a)).getRoleFromTask(xml);
					//test.execution();
					ITask t = r.makeTask(xml);
					//a.tasks.add(t);
					System.out.println(t.getDue());
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//(new RoleHandler(r,a)).getRoot(url);
				//(new RoleHandler(r,a)).getDue2(url);
			}
		});
		
		//Test Message ID
		btnTestMessageId.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				System.out.println("Message ID" + a.getMesID());
			}
		});
		
		
		//Test Ask Message
		btnTestAskmessage.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent arg0) {
			
				AskRole ar = new AskRole(a.getMesID(), "be.kul.osgi.ds.role1", a);
				a.messagehandler.addAskRole(ar);
				ar.AskforRole();
			}
		});
		
		//select a Task
		list_tasks.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent arg0) {
				if (arg0.getValueIsAdjusting()){
					ITask t = (ITask)list_tasks.getSelectedValue();
					TaskHandler th = new TaskHandler(a);
					//text_task_info.setText("Role : " + th.getRoleFromTask(t));
					IRole b = th.getRoleFromTask(t);
					//text_task_info.setText("Role : " + b..getSymbolicName());
					//text_task_info.setText("Capabilities : ");
					RoleHandler rh = new RoleHandler(b, a);
					text_task_info.setText(rh.getDependencies().toString());
					System.out.println("getitst");
				}
			}
		});
		
		//refresh task list
		btnTaskRefresh.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				//list_tasks.setListData(a.tasks);
			}
		});
		
		//Share Task
		btn_ShareTask.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				ITask task = (ITask)list_tasks.getSelectedValue();
				TaskHandler t = new TaskHandler(a);
//				t.shareTask(task);
			}
		});
	}
	
	public void refresh(){
		frmAgent.repaint();
	}

	public void messageReceived(MyEvent event) {
		text_console.append(event.mes + "\n");
	}
}